/**
 * @author Mirko Bordjoski
 */	
package org.piwik.managers
{
	import flash.events.EventDispatcher;
	
	import org.piwik.Piwik;
	import org.piwik.events.UserManagerEvent;
	import org.piwik.logic.Caller;
	import org.piwik.requests.PiwikRequest;	
	
	/**
	* The UserManager class enables to get token_auth from piwik analitycs. 
	* <p />
	* Token_auth is used for authentication in every Piwik request.
	*/
	public class UserManager extends EventDispatcher
	{
		
		
		/**
		* The URL of Piwik Analytics page. 
		*/
		public var 		baseURL:String;
		
		
		/**
		* Returning format of data.
		 * @see org.piwik.formats.PiwikFormats
		*/
		public var 		format:String 				= 		Piwik.XML;	
		
		
		/**
		* Show or hide busy cursor while loading the data. Default is <code>true</code> Flex only.
		*/	
		public var 		showBusyCursor:Boolean 		= 		true; 	
		
		
		/**
		* @private 
		*/
		private var 	_urlFull:String;
		
		
		
		
		/**
		* The UserManager class enables to get token_auth from piwik analitycs.
		* </p>
		* @note		 Token_auth is used for authentication in every Piwik request.
		* @param	 $baseURL		The URL of your Piwik home page.
		*/
		public function UserManager($baseURL:String = "http://piwik.org/demo/")
		{
			baseURL = $baseURL;
		}
		
		
		
		
		/**
		* Sends request to Piwik Analytics to get token_auth. 
		* <p />
		* @param	 $username		Username.
		* @param	 $password		Password.
		* @see		org.piwik.PiwikSetup
		*/
		public function getAuth($username:String, $password:String):void
		{
			_urlFull = baseURL; 
			_urlFull += PiwikRequest.MODULE_METHOD; //PiwikMethods.MODULE_METHOD;//MODULE_METHOD;
			_urlFull += "UsersManager.getTokenAuth&userLogin=";
			_urlFull += $username;
			_urlFull += "&password=";
			_urlFull += $password;
			_urlFull += PiwikRequest.FORMAT_RETURN; //PiwikMethods.FORMAT_RETURN;//FORMAT_RETURN;
			_urlFull += format;			
			
			Caller.makeCall(_urlFull, "getAuth", loaded, onIOError, onSecError, true, showBusyCursor);
		}
		
		
		
		/**
		* @private 
		* Dispatche UserManagerEvent.
		*/
		private function loaded(d:Object, who:String):void
		{
			var _auth:String = new XML(d).toString();
			dispatchEvent(new UserManagerEvent(UserManagerEvent.AUTH_LOADED, false, false,_auth, d, who));			
		}
		
		
		
		/**
		* @private 
		* Dispatche UserManagerEvent.
		*/
		private function onIOError(message:String):void
		{
			dispatchEvent(new UserManagerEvent(UserManagerEvent.IO_ERROR,false,false,null,"undefined",message));
		}
		
		
		
		/**
		* @private 
		* Dispatche UserManagerEvent.
		*/
		private function onSecError(message:String):void
		{
			dispatchEvent(new UserManagerEvent(UserManagerEvent.SECURITY_ERROR,false,false,null,"undefined",message));
		}
	}
}